package com.mutable.app.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Properties;


@Configuration
@EnableJpaRepositories(basePackages = "com.mutable.app.mapper2"    // 设置 repositories 包路径
        ,transactionManagerRef = "transaction2",entityManagerFactoryRef = "entityManagerFactory")
public class MysqlConfig2 {
    private static final Logger logger = LoggerFactory.getLogger(MysqlConfig2.class);

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "mysql.datasource.test2")
    public DataSource test2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean builder = new LocalContainerEntityManagerFactoryBean();
         builder.setDataSource(test2DataSource());
         builder.setJpaPropertyMap(jpaProperties.getProperties());
        builder.setPackagesToScan("com.mutable.app.entity");   // 实体类所在的包路径
//        builder.setPersistenceUnitName("primaryPersistenceUnit");
        builder.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        Properties pro = new Properties();
        pro.setProperty("hibernate.hbm2ddl.auto", "update");
        pro.setProperty("hibernate.show-sql", "true");
        builder.setJpaProperties(pro);
        return builder;
    }

    @Bean(name="entityManager")
    public EntityManager entityManager() {
        logger.info("init -- datasource2 completed!");
        return entityManagerFactory().getObject().createEntityManager();
    }

    @Bean(name = "transaction2")
    public PlatformTransactionManager transactionManager( ) {
        return new JpaTransactionManager(entityManagerFactory().getObject());
    }

}
